
package com.ymx.sdk.util;

import org.apache.commons.codec.binary.Base64;

import android.text.TextUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;

public class ArrayListAndStringUtil<E> {

    @SuppressWarnings("unchecked")
    public ArrayList<E> StringToArrayList(String wordBase64) {
        ArrayList<E> objects = new ArrayList<E>();
        if (TextUtils.isEmpty(wordBase64)) {
            return objects;
        }
        byte[] base64Bytes = Base64.decodeBase64(wordBase64.getBytes());
        ByteArrayInputStream bais = new ByteArrayInputStream(base64Bytes);
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(bais);
            objects = (ArrayList<E>) ois.readObject();
            if (ois != null) {
                ois.close();
            }
        } catch (StreamCorruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return objects;
    }

    public String ArrayListToString(ArrayList<E> objects) {
        if (objects == null) {
            return "";
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream(3000);
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(baos);
            oos.writeObject(objects);
            if (oos != null) {
                oos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(baos.toByteArray()));
    }

}
